package com.sxkf.core.third.im.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.sxkf.core.third.im.entity.AddFriend;
import com.sxkf.core.third.im.entity.SendMessage;
import com.sxkf.core.third.im.entity.SysNotice;
import com.sxkf.core.third.im.entity.UpdateUser;
import com.sxkf.core.third.im.service.YxService;
import com.sxkf.core.third.im.utils.CheckSumBuilder;
import com.sxkf.core.third.im.utils.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Slf4j
@Service
public class YxServiceImpl implements YxService {
    private static final String APP_KEY = "3697aa8dd71c6f15c5aaf008b3445868";

    private static final String DEFAULT_ACCOUNT = "246ba337ae0b1a0558a29c742b7c8082";

    /**
     * 注册云信IM账号
     * @param accountId 云信账号id（需保证唯一性） 本系统采用的是用户手机号
     * @return 云信token，不主动调用云信的刷新方法可以一直有效
     */
    @Override
    public String register(String accountId) {
        String url = "https://open.yunxinapi.com/im/v2/accounts";
        Map<String, String> bodies = new HashMap<>();
        bodies.put("account_id", accountId);
        JSONObject response = HttpUtil.post(url, getHeader(),JSON.toJSONString(bodies));
        log.info("response:{}",response);
        return response.getJSONObject("data").getString("token");
    }

    @Override
    public String refreshToken(String accountId) {
        String url = "https://open.yunxinapi.com/im/v2/accounts/"+accountId+"/actions/refresh_token";
        JSONObject response = HttpUtil.patch(url, getHeader(),null);
        log.info("response:{}",response);
        return response.getJSONObject("data").getString("token");
    }

    /**
     *
     * 发送单聊消息
     * @param senderId 发送者account_id
     * @param receiverId 接收者account_id
     * @param sendMessage 消息对象
     * @return 是否发送成功
     */
    @Override
    public Boolean sendMessage(String senderId, String receiverId, SendMessage sendMessage){
        String url = "https://open.yunxinapi.com/im/v2/conversations/"+senderId+"|1|"+receiverId+"/messages";
        JSONObject response = HttpUtil.post(url,getHeader(), JSON.toJSONString(sendMessage));
        log.info("res:{}",response);
        return response.getInteger("code")==200;
    }

    /**
     * 更新用户名片
     */
    @Override
    public Boolean updateUser(String accountId, UpdateUser user){
        String url = "https://open.yunxinapi.com/im/v2/users/"+accountId;
        JSONObject response = HttpUtil.patch(url,getHeader(), JSON.toJSONString(user));
        log.info("response:{}",response);
        return response.getInteger("code")==200;
    }

    /**
     * 发送广播消息
     */
    @Override
    public Boolean sendNotify(String content){
        String url = "POST https://open.yunxinapi.com/im/v2/broadcast_notification";
        Map<String, String> bodies = new HashMap<>();
        bodies.put("content", content);
        bodies.put("from_account_id",DEFAULT_ACCOUNT);
        bodies.put("offline_enabled","true");
        JSONObject response = HttpUtil.post(url,getHeader(), JSON.toJSONString(bodies));
        return response.getInteger("code")==200;
    }

    /**
     * 发送单聊系统通知
     * @param sysNotice 通知对象
     * @return 是否发送成功
     */
    @Override
    public Boolean sendSysNotice(SysNotice sysNotice){
        String url = "https://open.yunxinapi.com/im/v2/custom_notification";
        JSONObject response = HttpUtil.post(url, getHeader(), JSON.toJSONString(sysNotice));
        return response.getInteger("code")==200;
    }

    /**
     * @param accountId 发起黑名单操作的云信账号 ID。
     * @param contactAccountId 需要被列入黑名单的云信账号 ID
     */
    @Override
    public Boolean addBlack(String accountId, String contactAccountId){
        String url = "POST https://open.yunxinapi.com/im/v2/block_contacts";
        Map<String, String> bodies = new HashMap<>();
        bodies.put("account_id", accountId);
        bodies.put("contact_account_id",contactAccountId);
        JSONObject response = HttpUtil.post(url, getHeader(), JSON.toJSONString(bodies));
        return response.getInteger("code")==200;
    }

    /**
     *
     * @param accountId 发起移出黑名单操作的云信账号 ID。
     * @param contactAccountId 需要被移出黑名单的云信账号。
     */
    @Override
    public Boolean removeBlack(String accountId,String contactAccountId){
        String url = "https://open.yunxinapi.com/im/v2/block_contacts/"+accountId+"?contact_account_id="+contactAccountId;
        JSONObject response = HttpUtil.delete(url, getHeader());
        return response.getInteger("code")==200;
    }


    /**
     * @param type 申请添加好友的验证方式，1（默认）：直接添加，无需好友验证；2：需要对方验证通过。
     */
    @Override
    public Boolean addFriend(Integer type, AddFriend addFriend){
        String url = "https://open.yunxinapi.com/im/v2/friends?type="+type;
        JSONObject response = HttpUtil.post(url, getHeader(), JSON.toJSONString(addFriend));
        log.info("response:{}",response);
        return response.getInteger("code")==200;
    }

    @Override
    public Boolean removeFriend(String accountId, String friendAccountId) {
        String url = "https://open.yunxinapi.com/im/v2/friends/"+accountId+"?friend_account_id="+friendAccountId;
        System.out.println(url);
//        Map<String, String> bodies = new HashMap<>();
//        bodies.put("friend_account_id", friendAccountId);
        JSONObject response = HttpUtil.delete(url, getHeader());
        log.info("response:{}",response);
        return response.getInteger("code")==200;
    }

    @Override
    public Boolean updateFriend(String accountId,String friendAccountId,String alias){
        String url = "https://open.yunxinapi.com/im/v2/friends/"+accountId;
        Map<String, String> bodies = new HashMap<>();
        bodies.put("friend_account_id", friendAccountId);
        bodies.put("alias", alias);
        JSONObject response = HttpUtil.patch(url, getHeader(), JSON.toJSONString(bodies));
        log.info("response:{}",response);
        return response.getInteger("code")==200;
    }

    @Override
    public Boolean deleteRoom(Long cid){
        String url = "https://logic-dev.netease.im/v2/api/rooms/"+cid;
        JSONObject response = HttpUtil.delete(url, getHeader());
        return response.getInteger("code")==200;
    }

    /**
     * 订阅用户在线状态事件
     * @param accountId 订阅者account_id
     * @param accountIds 发布在线状态事件的用户账号列表。单次最多操作 100 个账号
     */
    @Override
    public Boolean queryUserOnline(String accountId, String[] accountIds){
        String url = "https://open.yunxinapi.com/im/v2/subscription/"+accountId+"?duration="+2592000L;
        Map<String, String> bodies = new HashMap<>();
        bodies.put("account_ids", JSON.toJSONString(accountIds));
        JSONObject response = HttpUtil.post(url,getHeader(),JSON.toJSONString(bodies));
        return response.getInteger("code")==200;
    }



    /**
     * 获取请求头
     * @return 请求头
     */
    private Map<String,String> getHeader(){
        String nonce = UUID.randomUUID().toString();
        String curTime = String.valueOf(new Date().getTime() / 1000);
        String checkSum = CheckSumBuilder.getCheckSum(nonce, curTime);
        Map<String, String> headers = new HashMap<>();
        headers.put("AppKey", APP_KEY);
        headers.put("Nonce", nonce);
        headers.put("CurTime", curTime);
        headers.put("CheckSum", checkSum);
        return headers;
    }
}
